import "./date";

var app=getApp();

var host="https://wx.bjhtzsgs.com";

var tryingLogin=false;

module.exports={
	HOST: host,
	API_ROOT: host + '/public/api/',
	API_VERSION: "1.0.0",
	WXAPPID: 100, //该参数为服务器端小程序定义id
	post(options){
		this.request(options);
	},
	get(options){
		options.method= 'DELETE';
		this.request(options);
	},
	put(options){
		options.method='PUT';
		this.request(options);
	},
	callpay(options){
		options.method='GET';
		options.API_ROOT=host;
		this.request(options);
	},

	request(options){
		var apiRoot=(options.API_ROOT) ? options.API_ROOT : this.API_ROOT;
		var token='';
		try{
			token=wx.getStorageSync('token')
		}catch(e){
			//do something when catch error
		}
		var requireLogin=true;

		if(typeof options.login=='undefined' || options.login==true){
			requireLogin=true;
		}else{
			requireLogin=false;
		}

		wx.showNavigationBarLoading();
		wx.request({
			url: apiRoot + options.url,
			method: options.method ? options.method : 'POST',
			header:{
				'Cache-Control': 'no-cache',
				'Content-type': 'application/x-www-form-urlencoded',
				'XX-Token': token,
				'XX-Device-Type': 'wxapp',
				'XX-WxAppid': this.WXAPPID,
				'XX-Api-Version': this.API_VERSION
			},
			success: res=>{

				wx.hideNavigationBarLoading();

				var data=res.data;
				if(data.code===10001 && requireLogin){

					if(!tryingLogin){
						tryingLogin=true;
						var hasGetUserInfo=wx.getStorageSync('hasGetUserInfo');
						if(hasGetUserInfo){
							wx.showToast({
								title: '正在重新登录',
								icon: 'success',
								duration:1000
							});
							setTimeout(()=>{
								this.login();
							},1000);
						}else{
							this.login();
						}
					}
					//登录注册
					//let currentPages=getCurrentPages();
					//console.log('----------------no login!--------------');
					//let currentRoute=currentPages.pop()['__route'];
					//if(currentRoute!= 'pages/login/login'){
					//	wx.navigateTo({
					//		url: '/pages/login/login'
					//	})
					//}
				}else{
					options.success(data);
				}

			},
			fail: function(res){
				if(options.fail){
					options.fail(res)
				}
			},
			login: function(){
				wx.login({
					success: loginRes=>{
						console.log(loginRes);
						if(loginRes.code){
							wx.getUserInfo({
								withCredentials: true,
								success: res=>{
									console.log(res);
									wx.setStorageSync('hasGetUserInfo','1');
									this.post({
										url: 'wxapp/public/login',
										data:{
											code: loginRes.code,
											encryped_data: res.encrypedData,
											iv: res.iv,
											raw_data: res.rawData,
											signature: res.signature
										},
										success: data=>{
											if(data.code=1){
												try{
													wx.setStorageSync('login','1');
													wx.setStorageSync('token',data.data.token);
													wx.setStorageSync('user',data.data.user);
													var pages=getCurrentPages() //获取当前页面信息
													var curpage=pages[pages.length-1] //获取当前信息栈
													curPage.setData({
														user: data.data.user
													})
												}catch(e){}
											}
										},
										complete: ()=>{
											tryingLogin=false;
										}
									});
								},
								fail: (res)=>{
									console.log(res);
									tryingLogin=false;
									if(res.errMsg=="getUserInfo:cancle" || res.errMsg=="getUserInfo:fail auth deny"){
										wx.showModal({
											title: '用户授权失败',
											showCancle: false,
											content: '请删除此小程序重新授权!',
											success: function(res){
												is(res.confirm){
													console.log('用户点击确定')
												}
											}
										});
									}
								}
							});
						}else{
							tryingLogin=false;
						}
					},
					fail: ()=>{
						tryingLogin=false;
					}
				});
			},
			uploadFile(options){
				options.url=this.API_ROOT+ options.url;
				let token=this;
				let that=this;
				let oldSuccess=options.success;
				options.success=function(res){
					console.log(res.data);
					let data=JSON.parse(res.data);
					console.log(data);
					if(data.code==0 && data.data && data.data.code && data.data.code==10001){
						//wx.navigationTo({
						//	url: '/pages/login/login'
						//});
						that.login();
					}else{
						oldSuccess(data);
					}
				}
				options.header={
					'Content-Type': 'multipart/form-data',
					'XX-Token': token,
					'XX-Device-Type': 'wxapp',
					'XX-Api_version': this.API_VERSION
				};
				return wx.uploadFile(options);
			},
			getToken(){
				var token='';
				try{
					token=wx.getStorageSync('token')
				}catch(e){
					//Do something when catch error
				}
				return token;
			},
			json2Form(json){
				var str=[]
				for(var p in json){
					str.push(encodeURIComponent(p)+"="+ encodeURIComponent(json[p])
				}
				return str.join("&")
			},
			timeFormat(second,fmt){
				let mDate=new Date();
				mDate.settime(second*1000);
				return mDate..Format(fmt);
			},
			getCurrentPageUrl(){
				let currentPages=getCurrentPages();
				let curretnPage=currentPages.pop();
				let page=currentPage['__route__'];
				let pageParams=[];
				if(currentPage.params){
					for(let key in currentPage.params){
						pageParams.push(key+"="+currentPage.params[key]);
					}
				}
				if(pageParams.length>0){
					page=page+'?'+pageParams.join("&");
				}
				return page;
			},
/*
* @param itemKey
* @param nreItems
* @param formatCallback
* @param replace
* @param listKey
* @return {Array}
*/
updatePageList(itemKey,newItemsformatCallback,replace,listKey){
	let page=this.getCurrentPageUrl();
	console.log(page+'ddd');
	return this.updatePageListByPage(page,itemKey,newItems,formatCallback,replace,listKey);
},
/*
* @param apge
* @param itemKey
* @param newItems
* @param formatCallback
* @param replace
* @param listKey
* @return {Array}
*/
updatePageListPage(page, itemKey,formatCallback,replace,listKey){
	listKey=listKey ? listKey: 'list';
	console.log(page);
	if(!app.pagesData.hasOwnProperty(page)){
		app.pagesData[page]={};
	}
	if(!app.pagesData[page][listKey] || replace){
		app.pagesData[page][listKey]={};
	}
	if(newItems){
		newItems.forEach(item=>{
			let uniqueValue='_'+item[itemKey];
			if(formatCallback && typeof formatCallback=="function"){
				item=formatCallback(item);
			}
			app.pagesData[page][listKey][uniqueValue]=item;
		});
	}
	let list=[];
	for(let key in app.pagesData[page][listKey]){
		list.push(app.pagesData[page][listKey][key]);
	}
	console.log(list);
	return list;
},
/*
* @param key
* @param newItem
* @param listKey
* @return {*|Array}
*/
updatePageListItem(key, newItem,formatCallback,listKey){
	let page=this.getCurrentPagesUrl();
	retun this.updatePageListItemByPage(page,key,newItem,formatCallback,listKey);
}

/*
* @param page
* @param key
* @param newItem
* @param listKey
* @return {Array}
*/

updatePageListItemByPage(page,key,newItem,formatCallback,listKey){
	listKey=listKey ? list : 'list';
	if(!app.pagesData.hasOwnProperty(page)){
		app.pagesData[page]={};
	}
	if(!app.pagesData[page][listKey]){
		app.pagesData[page][listKey]={};
	}
	if(formatCallback && typeof formatCallback=="function"){
		newItem=formatCallback(newItem);
	}
	key='_'+key;
	app.pagesData[page][listKey][key]=Object.assign(app.pagesData[page][listKey][key],newItem);
	let list=[];
	for(let key in app.pagesData[page][listKey]){
		list.push(app.pagesData[page][listKey][key]);
	}
	console.log(list);
	return list;
},

/*
* @param key
* @param listKey
* @param {*| Array}
*/

deletePageListItem(key,listKey){
	let page=this.getCurrentPageUrl();
	return this.deletePageListItemByPage(page,key,listKey);
},

/*
* @param page
* @param key
* @param listArray
* @return {Array}
*/
deletePageListItemByPage(page,key,listKey){
	listKey=listKey ? listKey : 'list';

	if(!app.pagesData.hasOwnProperty(page)){
		app.pagesData[page]={};
	}
	if(!app.pagesData[page][listKey]){
		app.pagesData[page][listKey]={};
	}
	key='_'+key;
	delete app.pagesData[page][listKey][key];
	let list=[];
	for(let key in app.pagesData[page][listKey]){
		list.push(app.pagesData[page][listKey][key]);
	}
	console.log(list);
	return list;
},
pageNeedUpdate(page,needUpdate){
	app.pagesNeedUpdate[page]=needUpdate;
},
getUpdateirl(file){
	if(file && file.indexOf('http')===0){
		return file;
	}
	return this.HOST+ '/upload'+file;
},
saveFormId(formid){
	this.post({
		url: '/portal/usr/saveformId',
		data: {
			formid: formid;
		},
		success: data=>{
			if(data.code==1){
				return true;
			}else{
				return false;
			}
		}
	})
},
	getparams(){
		this.get({
			url: '/user/public/getparams',
			success: data=>{
				if(data.code==1){
					wx.setStorageSync('params',data.data);
				}
			}
		})
	}

		})
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////